/**
 * 
 */
package org.rico.dynamic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.rico.dynamic.serivce.TaskService;
import org.rico.util.ScheduleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author rico
 *
 */
public class DynamicTaskTest {
	private static final Logger logger = LoggerFactory.getLogger(DynamicTaskTest.class);

	/**
	 * @param args
	 * @throws SchedulerException 
	 */
	public static void main(String[] args) throws SchedulerException {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-dynamic.xml");
		
		//SchedulerFactoryBean factoryBean = context.getBean(SchedulerFactoryBean.class);
		//Scheduler scheduler = factoryBean.getScheduler();

        TaskService taskService = (TaskService) context.getBean("taskService");
		Scheduler scheduler = (Scheduler) context.getBean("scheduler");
		
		Map<String, ScheduleJob> jobData = getTasks();
		List<ScheduleJob> jobs = new ArrayList<>(jobData.values());
		
		for (ScheduleJob job : jobs) {
			TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
			
			// 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			
			if (null == trigger) {
				// 不存在，创建一个
				JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(job.getJobName(), job.getJobGroup()).build();
				jobDetail.getJobDataMap().put("scheduleJob", job);
                jobDetail.getJobDataMap().put("taskService", taskService);
				
				// 按新的cronExpression表达式构建一个新的trigger
				trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
				scheduler.scheduleJob(jobDetail, trigger);
				
			} else {
				// Trigger已存在，那么更新相应的定时设置
				// 按新的cronExpression表达式重新构建trigger
				trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
				
				// 按新的trigger重新设置job执行
				scheduler.rescheduleJob(triggerKey, trigger);
			}
		}
	}
	
	/**
	 * 计划任务map
	 * @return
	 */
	private static Map<String, ScheduleJob> getTasks() {
		Map<String, ScheduleJob> jobMap = new HashMap<String, ScheduleJob>();
		
		for (int i=0; i<2; i++) {
			ScheduleJob job = new ScheduleJob();
			job.setJobId("10001#" + i);
			job.setJobName("data_import#" + i);
			job.setJobGroup("dataWork");
			job.setJobStatus("1");
			job.setCronExpression("0/5 * * * * ?");
			job.setDesc("数据导入任务");
			
			jobMap.put(job.getJobGroup() + "_" + job.getJobName(), job);
		}
		
		return jobMap;
	}

}
